<?php
/**
 * 描述：管理系统用户类。
 */
final class User
{
    const COOKIENAME_USERNAME='__shipinall_wy_zrx_dpo_admin_managementsystem_COOKIENAME_USERNAME';
    const COOKIENAME_PASSWORD='__shipinall_wy_zrx_dpo_admin_managementsystem_COOKIENAME_PASSWORD';
    const SESSIONNAME_LOGIN_CAPTCHA='__shipinall_wy_zrx_dpo_admin_managementsystem_sessionname_login_captcha';
    const SESSIONNAME_LOGIN_ERRORCOUNT='__shipinall_wy_zrx_dpo_admin_managementsystem_sessionname_login_errorcount';

    private static $PublicKey='_#$__A1sd&6_*&$&^sdf_as_d_45C5^*^Bshipinall.cn_FM(*&((9^((__c.l alsdkj86NV';

    private $Username=NULL;
    private $Password=NULL;
    private $Data=NULL;
    private $IsPasswordEncryption=NULL;
    private $VerifyStatus=NULL;

    public function __Construct($username,$password=NULL,$isPasswordEncryption=FALSE)
    {
        #设置用户名
        $this->Username=$username;
        $this->Password=$password;
        $this->IsPasswordEncryption=$isPasswordEncryption;

        #设计密码
        if($this->Password&&($this->IsPasswordEncryption==FALSE)){
            $this->Password=self::EncryptPassword($this->Password,$this->Username);
        }

        #获取数据
        $sql='select * from management_user where Username=?';
        $paramsValue=array($this->Username);
        $data=DB::PGetRows($sql,$paramsValue);
        if($data){
            $this->Data=$data[0];
        }
    }

    /**
     * 描述：获取私有属性
     */
    public function __Get($name)
    {
        switch($name)
        {
            case 'Username':
                return $this->Username;
            break;
            case 'Password':
                return $this->Password;
            break;
            case 'Data':
                return $this->Data;
            break;
            default :
                return NULL;
        }
    }

    /**
     * 描述：核实会员可用性
     */
    public function Verify()
    {

        #是否存在
        if(!$this->IsExists()){
            return $this->VerifyStatus='Inexistence';
        }

        #是否锁定
        if($this->IsLocked()){
            return $this->VerifyStatus='Locked';
        }

        #是否密码正确
        if(!$this->IsPassword()){
            return $this->VerifyStatus='PasswordWrong';
        }

        return $this->VerifyStatus='Normal';
    }

    /**
     * 描述：更新数据。
     */
    public function Update($data)
    {
        #更新数据表信息
        $result=DB::UpdateRowByField('management_user','Username:'.$this->Username,$data);

        #更新对象信息
        if($result)
        {
            if(array_key_exists('Password',$data))
            {
                $this->Password=$data['Password'];
            }            
            foreach($data as $key=>$value)
            {
                if($this->Data[$key])
                {
                    $this->Data[$key]=$value;
                }
            }
        }
    }

    /**
     * 描述：检测会员是不是存在。
     */
    public function IsExists()
    {
        #返回结果
        if($this->Data){
            return TRUE;
        }
        else{
            return FALSE;
        }
    }

    /**
     * 描述：检测密码是不是正确。
     */
    public function IsPassword()
    {
        if($this->Data)
        {
            if($this->Data['Password']==$this->Password){
                return TRUE;
            }
            else{
                return FALSE;
            }
        }
        else{
            return FALSE;
        }
    }

    /**
     * 描述：用户状态是否被锁定
     */
    public function IsLocked()
    {
        #获取数据
        $data=DB::PGetRows('select ID from management_user_locked where User=? limit 0,1',array
        (
            $this->Username
        ));

        if($data)
        {
            return TRUE;
        }
        else{
            return FALSE;
        }
    }

    /**
     * 描述：是否己经登录
     */
    public function IsLogin()
    {
        if(User::Session('Username')&&User::Session('Password'))
        {
            return TRUE;
        }
        return FALSE;
    }

    /**
     * 执行登录会员时作的操作
     */
    public function Login($cookiesExpire=NULL)
    {
        #用户名cookie写入
        Cookie::Set(self::COOKIENAME_USERNAME,$this->Username,$cookiesExpire);

        #密码cookie写入
        Cookie::Set(self::COOKIENAME_PASSWORD,$this->Password,$cookiesExpire);

        #更新数据库
        DB::PExec('update management_user set Login_Datetime=?,Login_Count=Login_Count+1 where Username=?',array
        (
            date('Y-m-d G:i:s'),
            $this->Username
        ));

        #清除未成功登录时记录的次数
        Session::Set(self::SESSIONNAME_LOGIN_ERRORCOUNT,NULL);
    }

    /**
     * 描述：记录登录错误。
     */
    public function Misregistration()
    {
        if(Session::Get(self::SESSIONNAME_LOGIN_ERRORCOUNT))
        {
            Session::Set(self::SESSIONNAME_LOGIN_ERRORCOUNT,Session::Get(self::SESSIONNAME_LOGIN_ERRORCOUNT)+1);
        }
        else{
            Session::Set(self::SESSIONNAME_LOGIN_ERRORCOUNT,1);
        }
    }

    /**
     * 会话注销
     */
    public function Logout()
    {
        #用户名
        Cookie::Delete(self::COOKIENAME_USERNAME);

        #密码
        Cookie::Delete(self::COOKIENAME_PASSWORD);
    }

    /**
     * 获取会话中的变量
     */
    public static function Session($name)
    {
        switch($name)
        {
            case 'Username':
                return Cookie::Get(self::COOKIENAME_USERNAME);
            break;
            case 'Password':
                return Cookie::Get(self::COOKIENAME_PASSWORD);
            break;
            default :
                return NULL;
        }
    }

    /**
     * 清除User会话
     */
    public static function Session_End()
    {
        Cookie::Delete(self::COOKIENAME_USERNAME);
        Cookie::Delete(self::COOKIENAME_PASSWORD);
    }

    /**
     * 检测是否需要进行验证码验证
     */
    public static function IsNeedCaptcha()
    {
        //当错误超过3次就需要验证码，返回真
        if(self::GetLoginErrorCount()>=3){
            return TRUE;
        }
        else{
            return FALSE;
        }
    }

    /**
     * 获取登录错误的次数
     */
    public static function GetLoginErrorCount()
    {
        $loginErrorCount=Session::Get(self::SESSIONNAME_LOGIN_ERRORCOUNT);
        return $loginErrorCount==NULL ? 0:$loginErrorCount;
    }

    /**
     * 加密密码的算法
     */
    public static function EncryptPassword($password,$factor)
    {
        $factor_a=bin2hex($factor[0]);
        $factor_b=bin2hex($factor[intval(strlen($factor)/2)]);
        $factor_c=bin2hex($factor[strlen($factor)-1]);
        $password=md5($factor_a.'__'.$password.'__'.$factor_b.'__'.self::$PublicKey.'__'.$factor_c);
        return $password;
    }

    /**
     * 权限检查
     */
    public static function Permission($permission)
    {
        $user=new User(User::Session('Username'),User::Session('Password'),TRUE);
        {
            $result=$user->Verify();
            if($result=='Normal')
            {
                //ACL
                if($user->Data['RoleID']==NULL)
                {
                    if(!in_array($permission,explode(',',$user->Data['Permissions'])))
                    {
                        exit('没有权限。');
                    }
                }
                //RABC-大于0证明不是admin,需要验证角色权限。等于0证明是admin，无需任何操作，权限无限。
                else if($user->Data['RoleID']>0)
                {
                    $permission_user=DB::GetRowByID('management_user_role','ID:'.$user->Data['RoleID']);
                    if($permission_user)
                    {
                        if(!in_array($permission,explode(',',$permission_user['Permissions'])))
                        {
                            exit('没有权限');
                        }
                    }
                    else
                    {
                        exit('没有权限!');
                    }
                }
            }
            else
            {
                if($result=='Locked')
                {
                    exit('己被锁定，请与管理员联系。');
                }
                else
                {
                    exit('用户名或密码错误，请重新登录。');
                }
            }
        }
        $user=NULL;
    }
	
	/**
     * 目录树
     */
	public static function Directory_Tree()
    {
		echo '<ul id="tree1" class="tree">';
		$User=new User(User::Session('Username'));
		$Permission=array();
		$Permission='1,2';
		if(strval($User->Data['RoleID'])!='0'){
			if($User->Data['RoleID']==NULL)
                {
                   $Permission=$User->Data['Permissions'];
                }
            else if($User->Data['RoleID']>0)
                {
                    $permission_user=DB::GetRowByID('management_user_role','ID:'.$User->Data['RoleID']);
                    if($permission_user)
                    {
                   		$Permission=$permission_user['Permissions'];
                    }
                }
		}
	$Modular=DB::GetRows('select Identifying,Name,Role,URL,Identifying_Parent from management_user_permission where Identifying_Parent is null order by RealSort asc');
		  $h=0;
		  for($i=0;$i<count($Modular);$i++)
		  { 		
		  if(in_array($Modular[$i]['Role'],explode(',',$Permission)) || strval($User->Data['RoleID'])=='0' ){
		  $h=$h+1;
		  if($h==1)
			  {
			 	 echo ' <li class="folder f-close first"> ';
			  }
		  else
			  {
		      	 echo ' <li class="folder f-close"> ';
			  }
		  echo '<span>'.$Modular[$i]['Name'].'</span>';
		  echo '<ul>';
		  #子模块
		  $Branch_Row=DB::GetRows('select Identifying,Name,Role,URL,Identifying_Parent,RealSort,Branch from management_user_permission where Identifying_Parent='.$Modular[$i]['Identifying'].' and Branch=1 order by Identifying asc ');
		   for($bi=0;$bi<count($Branch_Row);$bi++)
		   { 		
			 if(in_array($Branch_Row[$bi]['Role'],explode(',',$Permission)) || strval($User->Data['RoleID'])=='0' )
			 {
				echo ' <li class="folder f-close"> ';
				echo '<span>'.$Branch_Row[$bi]['Name'].'</span>';
		  		echo '<ul>';	
				$Branch_Function=DB::GetRows('select Identifying,Name,Role,URL,Identifying_Parent from management_user_permission where Identifying_Parent is not null and Identifying_Parent='.$Branch_Row[$bi]['Identifying'].' and IsList=1 order by Identifying asc');
           		for($j=0;$j<count($Branch_Function);$j++)
	          	{
					if(in_array($Branch_Function[$j]['Role'],explode(',',$Permission)) || strval($User->Data['RoleID'])=='0' )
					{
						echo '<li id="fxmorpherLink" class="doc">';
            			echo '<span><a href="modules/'.$Branch_Function[$j]['URL'].'" onclick="return Main.Panel.FromLink(this,\''.$Branch_Row[$bi]['Name'].'-'.$Branch_Function[$j]['Name'].'\');">'.$Branch_Function[$j]['Name'].'</a>';
               			echo '</span>';
            			echo '</li>';
					}
				}
				echo '</ul>';
    			echo '</li>';
			 }
		   }
			
    	$Function=DB::GetRows('select Identifying,Name,Role,URL,Identifying_Parent from management_user_permission where Identifying_Parent is not null and Identifying_Parent='.$Modular[$i]['Identifying'].' and IsList=1 order by Identifying asc');
           		for($j=0;$j<count($Function);$j++)
	          	{
					if(in_array($Function[$j]['Role'],explode(',',$Permission)) || strval($User->Data['RoleID'])=='0' ){
						echo '<li id="fxmorpherLink" class="doc">';
            			echo '<span><a href="modules/'.$Function[$j]['URL'].'" onclick="return Main.Panel.FromLink(this,\''.$Modular[$i]['Name'].'-'.$Function[$j]['Name'].'\');">'.$Function[$j]['Name'].'</a>';
               			echo '</span>';
            			echo '</li>';
					}
				}
        echo '</ul>';
     echo '</li>';
		 	 }
		   }
	echo '</ul>';
	}
	
	/**
     * 管理员操作统计
     */
	public static function Statistics_User($Role,$Talbe,$Classes)
    {
		$Statistics=DB::GetRows('select ID from `'.$Talbe.'` order by ID desc limit 1');
		$Cxecution=DB::GetRows('select Name,Identifying_Parent from `management_user_permission` where Role=\''.$Role.'\' limit 1');
		$Identifying_Parent=DB::GetRows('select Name from `management_user_permission` where Identifying=\''.$Cxecution[0]['Identifying_Parent'].'\' limit 1');
		DB::Insert('statistics',array
		(
			'UserName'=>User::Session('Username'),
			'Cxecution'=>$Identifying_Parent[0]['Name'].'--'.$Cxecution[0]['Name'],
			'MessageID'=>$Statistics[0]['ID'],
			'Classes'=>$Classes,
			'Datetime'=>date('Y-m-d')
		));
	}
	/**
     * 执行统计
	 *==================Statistics_Cxecution执行版块统计函数==================*
	 *Page_Value:页面值也是表名
	 *Cxecution:执行模块
	 *Period_Class:分组别名，按日、周、月、年分组。
	 *Period:分组时间
	 *Selects:部分sql语句
	 *Location:跳转页面参数
	 *Fields:统计版块名称
	 *List:判断传参页面
	 *Username:管理员名称
     */
	public static function Statistics_Cxecution($Page_Value,$Cxecution,$Period_Class,$Period,$Selects,$Location,$Fields=NULL,$List=NULL,$UserName=NULL)
    {
		if(!$UserName){ $UserName=User::Session('Username');}
		if(!$Fields){ $Fields='Cxecution';}
		$Wheres=' where '.$Fields.'=\''.$Cxecution.'\' ';
		$Wheres=$Wheres.' and UserName=\''.$UserName.'\'';
		$Order='group by '.$Period_Class.' order by '.$Period_Class.'';
		$Sqls=$Selects.$Wheres.$Order;
		$Account_Add=DB::GetRows($Sqls);
		//echo $Sqls;
		$Counts_Num=0;
		foreach($Account_Add as $Rows)
		{
			if($Period==$Rows[$Period_Class]) $Counts_Num=$Rows['countnum'];
		}
		if($Counts_Num>0 && $List)
		{
			echo '&nbsp;<a href="statistics.'.$Location.'.list.php?Username='.$UserName.'&Period_Time='.$Period.'">'.$Counts_Num.'条</a>';
		}
		elseif($Counts_Num>0){
			echo '&nbsp;<a href="statistics.'.$Location.'.content.list.php?id='.$Page_Value.'&Period_Class='.$Period_Class.'&Period='.$Period.'&Cxecution='.$Cxecution.'&UserName='.$UserName.'">'.$Counts_Num.'条</a>';	
		}else
		{
			echo '&nbsp;'.$Counts_Num.'条';
		}
	}
	/**
     * 总数统计
	 *==================Sum_Count总统计函数==================*
	 *Classes:统计版块名称
	 *Fields:统计板块字段
	 *Period_Class:分组别名，按日、周、月、年分组。
	 *Period:分组时间
	 *Username:管理员名称
     */
	public static function Sum_Count($Classes=NULL,$Fields=NULL,$Period_Class=NULL,$Period=NULL,$Username=NULL)
    {
		if(!$Username){
			$Username=User::Session('Username');
		}
		if(!$Classes&&!$Fields){
			$Wheres=' where 1=1';
		}else{
			$Wheres=' where UserName=\''.$Username.'\' and '.$Fields.'=\''.$Classes.'\'';	
		}
		if($Period_Class&&$Period){
			switch($Period_Class)
			{
				case 'days':
					$Selects='select ID,DATE_FORMAT(Datetime,\'%Y%年%m%月%d%日\') days from statistics';
					break;
				case 'weeks':
					$Selects='select ID,DATE_FORMAT(Datetime,\'%Y%年%u%周\') weeks from statistics';
					break;
				case 'months':
					$Selects='select ID,DATE_FORMAT(Datetime,\'%Y%年%m%月\') months from statistics';
					break;
				case 'years':
					$Selects='select ID,DATE_FORMAT(Datetime,\'%Y%年\') years from statistics';
					break;
				default:
					exit('参数错误');
			}
			$Sqls=$Selects.$Wheres;
		}
		else{
			$Sqls='select count(id) from `statistics`'.$Wheres;
		}
		$SumCount=DB::GetRows($Sqls);
		$Messages=0;
		if($Period_Class&&$Period){
			foreach($SumCount as $Rows)
			{
				if($Period==$Rows[$Period_Class]) $Messages+=1;
			}
		}
		else{
			$Messages=$SumCount[0][0];
		}
		if($Classes&&$Fields){
			echo '管理员 <font color="orange">'.$Username.'</font> 在 <font color="#003300">'.$Classes.'</font> 发布信息<font color="red">'.$Messages.'</font>条';
		}else{
			echo '目前管理员在后台发布所有信息共<font color="red">'.$Messages.'</font>条';
		}
	}
}
?>